#include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

/* At termination,properly close the terminal */
void exitfun()
{
	endwin();		//nc
}

/* Update the structure */
void updateFlakes(char **fieldln,int *rowln,int *colln)
{
	int numnew = 0;
	int row = 0; 
	int col = 0;
	int i = 0;
	char *field = *fieldln;
	
	getmaxyx(stdscr,row,col);  //get screen size //nc
	
	/* Create new field*/
	if(field == NULL || *rowln != row || *colln != col)
	{
		if(field != NULL)
		{
			free(field);
		}

		*fieldln = malloc(row * col);
		field = *fieldln;
		
		memset(field,0,row*col);
		*rowln = row;
		*colln = col;	
	}

	/* Apply gravity ! */

	memmove(&field[col],&field[0],(row-1)*col);
	memset(field,0,col);
	numnew = random()%(col/2);
	for(i = 0; i < numnew; i++)
	{
		field[random()%col] = 1;
	}
	
		
}


/*Let it snow*/
void drawScreen(char *field,int row,int col)
{
	clear();	//nc
	int x = 0;
	int y = 0;
	
	for(y = 0; y < row; y++)
	{
		
		for(x = 0; x < col; x++)
		{
			
			if(field[y*col + x] == 1)
			{
				mvaddch(y,x,'*'); //nc
			}
		}

	}

	refresh(); //nc
}


int main(int argc,char *argv[])
{
	char *field = NULL;
	int row = 0;
	int col = 0;
	
	initscr();
	atexit(exitfun);

	/* Eternnal snow*/
	
	while(1)
	{
		
		updateFlakes(&field,&row,&col);
		if(field == NULL)
		{
			
			break;
		}

	
		drawScreen(field,row,col);
		sleep(1);
	}

	return 0;
}
